<template>
    <view class="container" :style="themeColor">
        <view class="card-group">
            <card-group-cell
                label="头像"
                @click.native="chooseImage"
                :value="userInfo.HeadPortrait"
                :isImgView="true"
				:isShowRight="false"
				@wxHeadImg="wxHeadImg">
				<view>asldfjaklds</view></card-group-cell>
            <view class="custom-cell">
                <text class="cell-label">会员号</text>
                <view class="cell-main"
                    ><input
                        class="cell-input"
                        disabled
                        type="text"
                        v-model="userInfo.CardNumber"
                        placeholder="请填写姓名"
                /></view>
            </view>
            <view class="custom-cell">
                <text class="cell-label">姓名</text>
                <view class="cell-main"
                    ><input class="cell-input" type="text" v-model="userInfo.RealName" placeholder="请填写姓名"
                /></view>
            </view>
            <view class="custom-cell">
                <text class="cell-label">昵称</text>
                <view class="cell-main"
                    ><input class="cell-input" type="text" v-model="userInfo.NickName" placeholder="请填写昵称"
                /></view>
				<!-- #ifdef  MP-WEIXIN-->
				<view class="btn btn-gray headImgbtn"  @click.stop="wxHeadImg(2)">授权昵称</view>
				<!-- #endif -->
            </view>
            <view class="custom-cell">
                <text class="cell-label">{{registerFrom.Company.ViewName?registerFrom.Company.ViewName:'公司名称'}}</text>
                <view class="cell-main"
                    ><input class="cell-input" type="text" v-model="userInfo.CompanyName" placeholder="请填写公司名称"
                /></view>
            </view>
        </view>
        <view class="card-group">
            <view class="custom-cell">
                <text class="cell-label">手机号</text>
                <view class="cell-main">
                    <input
                        class="cell-input"
                        maxlength="11"
                        type="number"
                        v-model="userInfo.Tel"
                        placeholder="请填写手机号" />
                </view>
            </view>
            <view class="custom-cell">
                <text class="cell-label">地区选择</text>
                <view class="cell-main" @click="areaSelectFn">
                    <text class="cell-value">{{ regionName }}</text>
                    <uni-icons type="arrowright"></uni-icons>
                </view>
            </view>
            <view class="custom-cell">
                <textarea
                    class="cell-textarea"
                    placeholder="请填写详细地址(街道、楼牌号等)"
                    v-model="userInfo.Addr"></textarea>
                <uni-icons class="icon-location" type="location-filled" size="48" @click="getLoaction"></uni-icons>
            </view>
            <!-- <view class="custom-cell">
            	<text class="cell-label">微信号</text>
            	<view class="cell-main"><input class="cell-input" type="text" v-model="userInfo.wxnum"
            			placeholder="请填写微信号"></input></view>
            </view>
            <card-group-cell label="微信二维码" @click.native="chooseWxCode" :value="userInfo.wxcode" :isImgView="true"></card-group-cell> -->
        </view>

        <view class="bottom-wrapper">
            <button class="btn btn-success" @click="submit">保存</button>
        </view>
        <uni-popup ref="areaSelect" type="bottom" background-color="#fff" :safe-area="false">
            <area-select :address-data="userInfo" @pickArea="pickArea"></area-select>
        </uni-popup>
        <app-version ref="appVersion" :isAutoCheck="false" :appId="getAppId()"></app-version>
		<privacy-agreement></privacy-agreement>
		<uni-popup type="bottom" ref="authorizePop" background-color="#fff" :safe-area="false">
		    <view class="pop-pay-way">
		        <view class="title"><text style="padding:0;border: 0;font-size: 32rpx;color: #333;">选择图片</text></view>
		        <scroll-view scroll-y="true" class="add-pay-way-scroll">
		            <view class="pay-way">
		                <view class="pay-way-item" style="text-align: center;font-size: 30rpx;display: block;" @click="selecttype('camera')">拍照</view>
		                <view class="pay-way-item" style="text-align: center;font-size: 30rpx;display: block;" @click="selecttype('album')">从手机相册选择</view>
		            </view>
		        </scroll-view>
		        <button class="btn" style="margin:0;font-size: 30rpx;color:#666" @click="$refs.authorizePop.close()">取消</button>
		    </view>
		</uni-popup>
    </view>
</template>

<script>
import { GetMemberDetail, SubmitMemberDetail } from "@/service/api/member.js"
import { uploadImage } from "@/service/api/file.js"
import cardGroupCell from "@/components/common/cell/card-group-cell.vue"
import storage from "@/uni-sub-base/utils/storage.js"
import appVersion from "@/uni-sub-base/module/version/app-version.vue"
import areaSelect from "@/uni-sub-base/components/area-select/area-select.vue"
import { userAddressAddOrEdit, userAddressDelete, batchSmartParse } from "@/service/api/member.js"
import { GetRegisterInitData } from "@/service/api/web.js"
import { getLocation } from "@/uni-sub-base/utils/mapUtil.js"
import privacyAgreement from "@/components/privacy-agreement/privacy-agreement.vue"
import authorizeUtils from "@/utils/authorizeUtils.js"
import config from "@/config/config.js"
export default {
    components: {
        cardGroupCell,
        appVersion,
        areaSelect,
		privacyAgreement
    },
    data() {
        return {
            userInfo: {
                AddressName: "",
                RealName: "",
                Tel: "",
                Addr: "",
                ProvinceId: 0,
                ProvinceName: "",
                CityId: 0,
                CityName: "",
                RegionId: 0,
                RegionName: "",
                StreetId: 0,
                StreetName: "",
                Longitude: 0,
                Latitude: 0,
                ZipCode: null,
                HeadPortrait: "",
                NickName: "",
                CompanyName: "",
                ID: "", // 身份证号
                wxnum: "", // 微信号
                wxcode: "", //微信二维码
            },
            regionName: "请选择省、市、区",
			registerFrom: {
				Company:{}
			},
        }
    },
    mounted() {},
    onLoad() {
        this.info()
		this.GetRegisterInitData()//别名
    },
    methods: {
        info() {
            GetMemberDetail().then((res) => {
                this.userInfo = res.Data
                this.getRegionName()
            })
        },
		GetRegisterInitData(){
			GetRegisterInitData().then((res) => {
			    if (res.State == 1) {
			        if (res.Data.Infos && res.Data.Infos.length > 0) {
			            res.Data.Infos.forEach((item) => {
			                this.registerFrom[item.V_ItemParam] = {
			                    IsDisplay: item.IsDisplay,
			                    IsRequired: item.IsRequired,
								ViewName:item.ViewName
			                }
			            })
						console.log(this.registerFrom)
			        } 
			    }
			})
		},
        //修改头像
		//#ifdef APP
		async selecttype(openType) {
			const permissionType = openType === "album" ? "android.permission.READ_EXTERNAL_STORAGE" : "android.permission.CAMERA";
			let authFlag = await authorizeUtils.showAuthTipModal(permissionType);
			if (!authFlag) return;
			this.$refs.authorizePop.close()
			    // 此处处理各自业务 如：uni.chooseImage  
				let that = this
				uni.chooseImage({
				    count: 1, //默认9
				    sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
				    sourceType: [openType],
				    success: function (res) {
				        let type = "avatar"
				        that.upLoadPicFn(res, type)
				    },
					fail: (fail) => {
						if ([0, 11, 12].includes(fail.code)) return;
						authorizeUtils.showManualAuth(permissionType);
					}
				})
		},
		//#endif
		//#ifdef APP
		chooseImage() {
			this.$refs.authorizePop.open()
		},
		//#endif
		// #ifndef APP
        chooseImage() {
            let that = this
            uni.chooseImage({
                count: 1, //默认9
                sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ["album", "camera"], //从相册选择
                success: function (res) {
                    let type = "avatar"
                    that.upLoadPicFn(res, type)
                },
            })
        },
		//#endif
        //上传微信二维码
        chooseWxCode() {
            let that = this
            uni.chooseImage({
                count: 1, //默认9
                sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ["album", "camera"], //从相册选择
                success: function (res) {
                    let type = "code"
                    that.upLoadPicFn(res, type)
                },
            })
        },
        //上传图片
        upLoadPicFn(files, type) {
            let param = {
                filePath: files.tempFilePaths[0],
                formData: {},
            }
            uploadImage(param).then((e) => {
                if (e.Data) {
                    if (type == "avatar") {
                        this.userInfo.HeadPortrait = this.easyGetImgUrl(e.Data.FullPath)
                    } else {
                        this.userInfo.wxcode = this.easyGetImgUrl(e.Data.FullPath)
                    }
                }
            })
        },
        //提交
        submit() {
            //必填值校验
            if (this.userInfo.RealName.trim() == "") {
                this.easyToast("请填写姓名")
                return
            }
            if (this.userInfo.Tel.trim() == "") {
                this.easyToast("请填写手机号")
                return
            }
            if (this.userInfo.Tel.length < 11) {
                this.easyToast("请正确填写手机号")
                return
            }
			
			if (this.regionName.length <= 8) {
			    this.easyToast("请选择地区")
			    return
			}
			if (this.userInfo.Addr=="") {
			    this.easyToast("请填写详细地址")
			    return
			}
            if (this.userInfo.Addr.trim() == "") {
                this.easyToast("请填写详细地址")
                return
            }
            SubmitMemberDetail(this.userInfo).then((res) => {
                if (res.State) {
                    this.easyToast("保存成功")
                    //更新缓存里面数据
                    let userInfo = storage.getCache("userInfo")
                    userInfo.HeadPortrait = this.userInfo.HeadPortrait
                    userInfo.NickName = this.userInfo.NickName
                    storage.setCache("userInfo", userInfo)
                    this.easyGoBack()
                }
            })
        },

        //选择地区
        areaSelectFn() {
            this.$refs.areaSelect.open()
        },
        //选择地区回调
        pickArea(data) {
            this.$refs.areaSelect.close()
            this.userInfo = Object.assign(this.userInfo, data)
            this.getRegionName()
        },
        getRegionName() {
            let line = "-"
            this.regionName = `${this.userInfo.ProvinceName || ""}-${this.userInfo.CityName || ""}${
                this.userInfo.RegionName ? line + this.userInfo.RegionName : ""
            }${this.userInfo.StreetName ? line + this.userInfo.StreetName : ""}`
            // this.userInfo.ProvinceName?this.userInfo.ProvinceName:'' +
            // this.userInfo.CityName?"-"+this.userInfo.CityName:''+
            // this.userInfo.RegionName?"-"+this.userInfo.RegionName:''+
            // this.userInfo.StreetName?"-"+this.userInfo.StreetName:''
        },
		//#ifdef APP
		 getLoaction() {
		        return new Promise(async (resolve) => {
		            let authFlag = await authorizeUtils.showAuthTipModal("android.permission.ACCESS_FINE_LOCATION")
		            if (!authFlag) return resolve(null)
					let that = this
					uni.chooseLocation({
						success: function (res) {
							console.log(res)
							console.log("位置名称：" + res.name)
							console.log("详细地址：" + res.address)
							console.log("纬度：" + res.latitude)
							console.log("经度：" + res.longitude)
							that.getAppP(res)
							that.userInfo.Addr = res.name
							that.userInfo.Longitude = res.longitude
							that.userInfo.Latitude = res.latitude
						},
						fail: (fail) => {
						    this.hideLoading()
						    authorizeUtils.showManualAuth("android.permission.ACCESS_FINE_LOCATION")
						    return resolve(null)
						}
						
					})
		        })
		    },
		//#endif
		// #ifndef APP
        getLoaction() {
            //#ifdef MP-WEIXIN
            this.getCenterLocation()
            //#endif
            //#ifdef APP
            uni.navigateTo({
                url: "/pages_me/packet/map/map-poi",
                events: {
                    getSelectData: (data) => {
                        this.getAppP(data)
                        this.userInfo.Longitude = data.location.longitude
                        this.userInfo.Latitude = data.location.latitude
                        this.userInfo.Addr = data.name + data.address.replace(/\\/g, "")
                    },
                },
            })
            //#endif
            //#ifdef H5
            getLocation(
                (res) => {
                    if (res) {
                        this.userInfo.Addr = res.address.street + res.address.streetNum

                        this.getP(res.address)
                    }
                },
                (err) => {
                    console.log(err)
                },
            )
            //#endif
        },
		//#endif
        getCenterLocation() {
            var that = this
            wx.authorize({
                scope: "scope.userLocation",
                complete: function (res) {
                    wx.chooseLocation({
                        success(str) {
                            var getAddressUrl ='https://restapi.amap.com/v3/geocode/regeo?output=JSON&location='+str.longitude+','+str.latitude +
                                                            "&key=" +config.aMapKey.wx
                            wx.request({
                                url: getAddressUrl,
                                success: function (result) {
                                   var province = result.data.regeocode.addressComponent.province
                                   var city = result.data.regeocode.addressComponent.city
                                   var district = result.data.regeocode.addressComponent.district
                                   var address = result.data.regeocode.addressComponent.streetNumber.street+result.data.regeocode.addressComponent.streetNumber.number
                                   
                                    that.userInfo.Addr = address
                                    that.userInfo.Longitude = str.longitude
                                    that.userInfo.Latitude = str.latitude
                                    that.getmapP(
                                        result.data.regeocode.addressComponent,
                                        address,
                                    )
                                },
                            })
                        },
                    })
                },
            })
        },
        getP(res) {
            let item = {
                ContactAddress: res.street + res.streetNum,
                ProvinceName: res.province,
                CityName: res.city,
                RegionName: res.district,
                StreeName: res.street,
                ContactName: this.userInfo.RealName || "aaa",
                ContactTel: this.userInfo.Tel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        getAppP(res) {
            let item = {
                ContactAddress: res.address,
                ProvinceName: res.province,
                CityName: res.city,
                RegionName: res.district,
                ContactName: this.userInfo.RealName || "aaa",
                ContactTel: this.userInfo.Tel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        getmapP(res, resStreeName) {
            let item = {
                ContactAddress: resStreeName,
                ProvinceName: res.province,
                CityName: res.city,
                AreaName: res.district,
                StreetName: res.township,
                ContactName: this.userInfo.RealName || "aaa",
                ContactTel: this.userInfo.Tel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        //智能识别
        batchSmartParse(param) {
            batchSmartParse(param).then((res) => {
                if (res.Data && res.Data.list && res.Data.list.length > 0) {
                    let result = res.Data.list[0]
                    this.userInfo.ProvinceId = result.ProvinceId
                    this.userInfo.ProvinceName = result.ProvinceName
                    this.userInfo.CityId = result.CityId
                    this.userInfo.CityName = result.CityName
                    this.userInfo.RegionId = result.AreaId
                    this.userInfo.RegionName = result.AreaName
                    this.userInfo.StreetId = result.StreetId
                    this.userInfo.StreetName = result.StreetName
                    this.getRegionName()
                }
            })
        },
        getVersion() {
            //#ifdef APP-PLUS
            let ver = plus.runtime.version

            return ver
            //#endif
            return ""
        },
        checkVersion() {
            this.$refs.appVersion.checkVersion()
        },
		wxHeadImg(num){
			//num 1 授权头像  2授权昵称
			this.requestAuthorize(num);
		},
		requestAuthorize(num) {
			let that = this;
		  wx.getSetting({
			success(res) {
			  if (!res.authSetting['scope.userInfo']) {
				// 还未授权，发起授权请求
				wx.authorize({
				  scope: 'scope.userInfo',
				  success() {
					// 用户已同意授权，可以直接调用 getUserProfile 获取头像等信息
					wx.getUserProfile({
					  desc: '用于完善会员资料', //这个也很重要
					  success: (userInfoRes) => {
							// 获取用户信息成功
							if(num==1){
								that.userInfo.HeadPortrait = userInfoRes.userInfo.avatarUrl
							}else{
								that.userInfo.NickName = userInfoRes.userInfo.nickName
							}
							
							console.log(userInfoRes.userInfo);
						  },
						  fail: (error) => {
							// 获取用户信息失败
							console.error('获取用户信息失败', error);
						  }
					})
				  },
				  fail() {
					// 用户拒绝授权，给出提示
					uni.showModal({
					  title: '用户未授权',
					  content: '如需正常使用功能，请按确定并在设置中允许获取头像等信息',
					  success: (modalRes) => {
						if (modalRes.confirm) {
						  // 引导用户去设置中开启权限
						  uni.openSetting();
						}
					  }
					});
				  }
				});
			  }else{
				 wx.getUserProfile({
				   desc: '用于完善会员资料', //这个也很重要
				   success: (userInfoRes) => {
				 		// 获取用户信息成功
				 		if(num==1){
				 			that.userInfo.HeadPortrait = userInfoRes.userInfo.avatarUrl
				 		}else{
				 			that.userInfo.NickName = userInfoRes.userInfo.nickName
				 		}
				 		console.log(userInfoRes.userInfo);
				 	  },
				 	  fail: (error) => {
				 		// 获取用户信息失败
				 		console.error('获取用户信息失败', error);
				 	  }
				 })
			  }
			}
		  });
		},
    },
}
</script>

<style lang="scss">
.container {
    padding: $app-page-padding 0;
    .card-group-cell .image {
        width: 90rpx;
        height: 90rpx;
        border-radius: 90rpx;
    }
    .card-group-cell {
        margin-left: 32rpx;
        border-color: $uni-border-bottom-color;
        .uni-icons {
            color: #ccc;
        }
        text,
        .label,
        .input {
            font-size: $font-size-32;
        }
    }
}
.card-group {
    margin-bottom: 20rpx;
    background: $color-white;
    border-radius: $border-radius-10;
}
.bottom-wrapper {
    padding: 0 $app-page-padding;
}
.btn {
    margin-top: 40rpx;
    height: 88rpx;
    font-size: 36rpx;
}
.bottom-pop {
    background: $color-white;
    padding: $app-page-padding;
    border-radius: $border-radius-30 $border-radius-30 0 0;

    .title {
        margin-top: 20rpx;
        display: flex;
        justify-content: center;
        margin-bottom: 20rpx;
        font-size: $font-size-32;
        font-weight: 600;
    }
    .actions {
        display: flex;
        flex-direction: row;
        margin-bottom: 48rpx;
        .btn {
            width: 220rpx;
        }
    }
}
.custom-cell {
    display: flex;
    flex-direction: row;
    align-items: center;
    min-height: 66rpx;
    padding: $app-page-padding;
    padding-left: 0;
    margin-left: 32rpx;
    border-bottom: solid 1rpx $uni-border-bottom-color;

    &:last-child {
        border-bottom: 0;
    }

    .cell-label {
        display: flex;
        flex: 1;
        font-size: $font-size-32;
    }

    .cell-main {
        display: flex;
        align-items: center;
        // flex: 3;
        overflow: hidden;

        .cell-value {
            // flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            color: $app-color-text-desc;
            font-size: $font-size-32;
        }

        .cell-input {
            color: $app-color-text-desc;
            font-size: $font-size-32;
            text-align: right;
        }
    }

    .cell-textarea {
        height: 160rpx;
        color: $app-color-text-desc;
        font-size: $font-size-32;
    }

    .icon-location {
        padding: $app-page-padding;
        margin-right: -$app-page-padding;
    }
}

.card-cell {
    margin-bottom: 40rpx;
}

.cell-switch {
    transform: scale(0.8);
}
.headImgbtn{
	margin-left: 24rpx;
	height: 42rpx;
	font-size: 24rpx;
	margin-top: 0;
}
</style>
